package cn.edu.stu.interception;

import cn.edu.stu.service.ConfService;
import cn.edu.stu.tool.Constants;
import cn.edu.stu.tool.JWTUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author Karl
 * @Date 2022/12/12 - 12:09
 */
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            myForward("请先登录！",request,response);
            return false;
        }
        Map<String,String> map = null;
        try {
            map = JWTUtil.verify(token);
        } catch (TokenExpiredException e) {
            myForward("token已过期，请重新登录！",request,response);
            return false;
        }catch (Exception e){
            myForward("token错误！",request,response);
            return false;
        }
        //将他的个人信息存到请求对象的属性域中
        try {
            request.setAttribute("username",map.get("username"));
            request.setAttribute("userid",Long.parseLong(map.get("userid")));
        } catch (Exception e) {
            myForward("请先登录！！",request,response);
            return false;
        }

        return true;
    }

    private void myForward(String msg, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("error", msg);
        request.getRequestDispatcher("/myError").forward(request, response);
    }
}
